﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dukou.Domain
{
    public abstract class HibernateEntity<TId> : IEntity<TId>
    {
        public virtual TId Id { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual bool Equals(HibernateEntity<TId> entity)
        {
            if (entity == null)
            {
                return false;
            }
            if (ReferenceEquals(this, entity))
            {
                return true;
            }
            if (!IsTransient(this) && !IsTransient(entity) && Equals(Id, entity.Id))
            {
                var otherType = entity.GetUnproxiedType();
                var thisType = GetUnproxiedType();
                return thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType);
            }
            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static bool IsTransient(HibernateEntity<TId> obj)
        {
            return obj != null && obj.Id.Equals(default(TId));
        }

        private Type GetUnproxiedType()
        {
            return GetType();
        }

        public override int GetHashCode()
        {
            if (Id.Equals(default(TId)))
            {
                return base.GetHashCode();
            }
            return Id.GetHashCode();
        }
    }
}
